#include <print.h>
#include <printf.h>
#include <types.h>
#include <mmu.h>
#include <pmap.h>

void exc_hand_reserved(u_int64_t cause, u_int64_t badvaddr, u_int64_t epc, u_int64_t satp_value)
{
	int r = -1;
	if (cause == 5 || cause == 7 || cause == 13 || cause == 15) {
	//	r = page_fault(cause, badvaddr, satp_value);
	}
	if (r == 0) {
	//	return;
	}
	
	printf("Exception!!!\n");
	printf("Cause:%lx, Bad vaddr:0x%lx, epc:0x%lx!!!\n", cause, badvaddr, epc);
	panic("Exception!!!!!!!!!!!!!");
}

int page_fault(u_int64_t cause, u_int64_t badvaddr, u_int64_t satp_value)
{
	Pte *vpt2, *vpt1, *vpt0, vpt0_ent;
	vpt2 = (Pte *)(satp_value << 20);
	if ((vpt2[VPN2(badvaddr)] & PTE_V) == 0) {
		pageout(badvaddr, vpt2);
		return 0;
	} else {
		vpt1 = (Pte *)PTE_TO_PADDR(vpt2[VPN2(badvaddr)]);
		if ((vpt1[VPN1(badvaddr)] & PTE_V) == 0) {
			pageout(badvaddr, vpt2);
			return 0;
		} else {
			vpt0 = (Pte *)PTE_TO_PADDR(vpt1[VPN1(badvaddr)]);
			if ((vpt0[VPN0(badvaddr)] & PTE_V) == 0) {
				pageout(badvaddr, vpt2);
				return 0;
			} else {
				vpt0_ent = vpt0[VPN0(badvaddr)];
			}
		}
	}
	if ((cause == 7 || cause == 15) && ((vpt0_ent & PTE_COW) != 0)) {
		
	}
}
